<template>
	<view style="margin-top: 30rpx;padding: 0 20rpx;">
		<uni-title type="h2" title="物品详情"></uni-title>
		<uni-forms ref="form" labelAlign="center" :modelValue="houseData" :rules="rules">
			<uni-forms-item label="物品名" name="name">
				<uni-easyinput type="text" v-model="houseData.name" placeholder="请输入姓名" />
			</uni-forms-item>
			<uni-forms-item label="季节" name="season">
				<uni-segmented-control :current="houseData.season - 1" :values='seasonBase' @clickItem="onSeasonCheck"
					styleType="button" activeColor="#0275d9" />
			</uni-forms-item>
			<uni-forms-item label="物品图" name="img">
				<u-upload
					:fileList="houseImgBase" 
					:maxCount="1" 
					@afterRead="onImageLoad"
					@delete="onImageDelect"
					width="250"
					height="250"
					/>
			</uni-forms-item>
			<uni-forms-item label="详情" name="shopAbout">
				<uni-easyinput type="textarea" v-model="houseData.note"></uni-easyinput>
			</uni-forms-item>
		</uni-forms>
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog 
			:before-close="true"
			type="info" 
			title="添加分类" 
			:duration="2000" 
			@confirm="onAddClassify"
			@close="onCloseAddClassify">
				<AddClassify ref="addClassify"></AddClassify>
			</uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="popupItem" type="dialog">
			<uni-popup-dialog 
			:before-close="true"
			type="info" 
			title="添加分类项" 
			:duration="2000" 
			@confirm="onAddClassifyItem"
			@close="onCloseAddClassifyItem">
				<AddClassifyItem ref="addClassifyItem"></AddClassifyItem>
			</uni-popup-dialog>
		</uni-popup>
		<uni-title type="h2" title="物品分类"></uni-title>
		<view class="house_list" v-for="item,pIndex in houseData.class" :key="pIndex">
			<view class="close" @click="deleteClass(pIndex)">
				X
			</view>
			<view class="title">
				<uni-title type="h3" :title="item.name"></uni-title>
			</view>
			<view class="note">
				{{item.note}}
			</view>
			<scroll-view class="class_item" scroll-x scroll-y>

				<view class="class_item_add" @click="openItem(pIndex)">
					
				</view>
				<view class="class_item_box" v-for="elmItem,index in item.detail" :key="index">
					<view class="close" @click="deleteClassItem(pIndex,index)">
						X
					</view>
					<view class="img">
						<img :src="elmItem.img || 'https://www.hualigs.cn/image/632adbc0e890e.jpg'">
					</view>
					<view class="title">
						{{elmItem.name}}
					</view>
					<view class="price">
						￥{{elmItem.price}}
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="class_add" @click="open">
			+
		</view>
		<view style="margin-top: 30rpx;"></view>
		<u-button type="warning" @click="submit()" color="rgb(2, 117, 217)">提交</u-button>
		<view style="margin-top: 30rpx;"></view>
		<u-modal
			:show="classErrorModlelShow" 
			title="校验错误" 
			content='请保证至少有有一个分类，每个分类至少有一个分类项' 
			@confirm="classErrorModlelShow = false"
		></u-modal>
		
	</view>
</template>


<script>
	import { uploadImg } from '@/tools/upload.js'
	import { addHouse } from "@/request/index.js"
	const checkClass  = (list = []) => {
		if(list.length > 0){
			const res = list.filter(item => {
				return item.detail.length === 0
			})
			if (res.length > 0) {
				return res.reduce((p,c)=>{
					return `${c.name} ${p}`
				},"")
			}
		}else{
			return "undefined"
		}
	}
	export default {
		data() {
			return {
				// 表单数据
				houseData: {
					id:'',
					name: '',
					season: 5,
					img:"",
					class:[],
					note:""
				},
				classErrorModlelShow:false,
				houseImgBase:[],
				seasonBase: ["春", "夏", "秋", "冬", "全"],
				classIndex:-1,
				rules: {
					name: {
						rules: [{
								required: true,
								errorMessage: '请输入物品标题',
							}
						]
					},
					img:{
						rules:[
							{
								validateFunction:(_1,value,_2,callback)=>{
									const { houseImgBase } = this
									if (houseImgBase[0]) {
										if (houseImgBase[0].status){
											return false
										}
									}
									return true
								},
								errorMessage: '图片上传中'
							}
						]
					}
				}
			}
		},
		onHide() {
			Object.assign(this.$data, this.$options.data())
		},
		onShow() {
			const { rewrite } = this.$Route.query
			if(rewrite){
				let { $reData:reData } = uni
				if(reData){
					reData = JSON.parse(JSON.stringify(reData))
					let { list,img } = reData
					if(list){
						delete reData.list
						list = list.map(item => {
							item.detail = item.list
							delete item.list
							return item
						})
						reData.class = list
					}
					if(img){
						this.houseImgBase.push({url:img})
					}
					this.houseData = reData
				}else{
					uni.switchTab({
						url:"/pages/addHouse/addHouse"
					})
				}
			}
		},
		methods: {
			submit() {
				this.$refs.form.validate().then(async _ => {
					const ckeckRes = checkClass(this.houseData.class)
					if (!ckeckRes){
						try{
							const id = await addHouse(this.houseData)
							uni.showModal({
								title:"提交成功，是否前往详情页?",
								success:({confirm})=> {
									uni.$rIndex = true
									if(confirm){
										this.$Router.push(`/pages/initTheInventory/initTheInventory?id=${id}`)
									}else{
										Object.assign(this.$data, this.$options.data())
									}
								}
							})
						}catch{
							uni.showToast({
								title:"错误" + JSON.parse(err),
								icon:'error'
							})
						}
					}else{
						this.classErrorModlelShow = true
					}
				}).catch(err => {
					
				})
			},
			async  onImageLoad({file}){
				const { url } = file
				this.houseImgBase = [{
					...file,
					status: 'uploading',
					message: '上传中'
				}]
				try{
					const imgUrl = await uploadImg(url) 
					this.houseImgBase = [
						{url:imgUrl}
					]
					this.houseData.img = imgUrl
				}catch(e){
					this.onImageDelect()
					uni.showToast({
						title:"图片上传失败,请稍后重试",
						icon:'error'
					})
				}
			},
			onImageDelect(){
				this.houseImgBase = []
			},
			onSeasonCheck(value){
				this.houseData.season = value.currentIndex + 1
			},
			open() {
				this.$refs.popup.open()
			},
			deleteClass(index){
				this.houseData.class.splice(index,1)
			},
			deleteClassItem(classIndex,itemIndex){
				this.houseData.class[classIndex].detail.splice(itemIndex,1)
			},
			openItem(classIndex){
				this.classIndex = classIndex
				this.$refs.popupItem.open()
			},
			async onAddClassify() {
				try{
					const res = await this.$refs.addClassify.submit()
					this.houseData.class.push({...res,detail:[]})
					this.onCloseAddClassify()
				}catch{}
			},
			
			onCloseAddClassify() {
				this.$refs.popup.close()
			},
			async onAddClassifyItem(){
				try{
					const { $refs,houseData,classIndex } = this
					const res = await $refs.addClassifyItem.submit()
					houseData.class[classIndex].detail.push(res)
					this.onCloseAddClassifyItem()
				}catch{}
			},
			onCloseAddClassifyItem(){
				this.classIndex = -1
				this.$refs.popupItem.close()
			}
		}
	}
</script>

<style lang="scss">
	.uni-forms-item__label {
		justify-content: center !important;
	}

	/deep/.file-picker__box {
		width: 400rpx !important;
		height: 400rpx !important;
	}
	.class_add{
		width: 100%;
		height: 150rpx;
		border-radius: 15rpx;
		background-color: rgb(248, 249, 249);
		border: 5px rgb(2, 117, 217) dashed;
		box-sizing: border-box;
		font-size: 100rpx;
		text-align: center;
		line-height: 136rpx;
		color: rgb(2, 117, 217);
	}
	.house_list{
		width: 100%;
		height: 444rpx;
		background-color: rgb(248, 249, 249);
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 5rpx 3rpx 5rpx 3rpx gray;
		overflow: hidden;
		position: relative;
		& > .close{
			position: absolute;
			right: 20rpx;
			top: 20rpx;
			font-weight: 700;
			color: rgb(2, 117, 217);
		}
		& > .title{
			padding: 0 20rpx ;
		}
		& > .note{
			white-space:nowrap;
			overflow: hidden;
			text-overflow:ellipsis;
			display: block;
			width: 100%;
			padding: 0 20rpx;
			font-size: 26rpx;
			color: #5b5b5b;
		}
	
		.class_item{
			width: 100%;
			height: 320rpx;
			margin-top: 20rpx;
			white-space: nowrap;
			
			&_box > .close{
				position: absolute;
				right: 20rpx;
				top: 10rpx;
				font-weight: 700;
				color: rgb(2, 117, 217);
			}
			&_box{
				position: relative;
			}
			
			&_box,&_add{
				box-sizing: border-box;
				display: inline-block;
				height: 300rpx;
				width: 200rpx;
				background-color: rgb(2, 117, 217);
				border-radius: 20rpx;
				margin: 0 10rpx;
				padding: 0 10rpx;
				overflow: hidden;
				.img{
					width: 100%;
					height: 180rpx;
					margin: 10rpx 0 ;
					border-radius: 10rpx;
					overflow: hidden;
					padding: 9rpx;
					background-color: white;
					box-sizing: border-box;
					img{
						width: 100%;
						height: 100%;
					}
				}
				
				& > .title{
					font-size: 30rpx;
					color: white;
					width: 100%;
					white-space:nowrap;
					overflow: hidden;
					text-overflow:ellipsis;
					display: block;
				}
				& > .price{
					margin-top: 10rpx;
					font-size: 30rpx;
					color: #ff494c;
					font-weight: 700;
				}
			}
			&_add{
				background-color: white;
				border: 3px dashed rgb(2, 117, 217);
				position: relative;
				&::after{
					content: "+";
					display: block;
					position: absolute;
					top: 50%;
					left: 50%;
					color: rgb(2, 117, 217);
					transform: translate(-50%,-50%);
					font-weight: 1000;
					font-size: 50rpx;
				}
			}
			
		}
	}
</style>
